import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { User, AppState } from '@/types';

// 错误类型定义
interface AppError {
  type: 'websocket' | 'api' | 'auth' | 'network' | 'unknown';
  message: string;
  timestamp: string;
  code?: string;
  details?: any;
}

export const useAppStore = defineStore('app', () => {
  // 状态
  const user = ref<User | null>(null);
  const token = ref<string | null>(null);
  const currentDeviceId = ref<string | null>(null);
  const isConnected = ref(false);
  const isLoading = ref(false);
  const lastError = ref<AppError | null>(null);

  // 计算属性
  const isLoggedIn = computed(() => !!user.value && !!token.value);
  const hasDevice = computed(() => !!currentDeviceId.value);

  // 方法
  const setUser = (newUser: User | null) => {
    user.value = newUser;
    if (newUser) {
      localStorage.setItem('smartinput-mobile-user', JSON.stringify(newUser));
    } else {
      localStorage.removeItem('smartinput-mobile-user');
    }
  };

  const setToken = (newToken: string | null) => {
    token.value = newToken;
    if (newToken) {
      localStorage.setItem('smartinput-mobile-token', newToken);
    } else {
      localStorage.removeItem('smartinput-mobile-token');
    }
  };

  const setCurrentDeviceId = (deviceId: string | null) => {
    currentDeviceId.value = deviceId;
    if (deviceId) {
      localStorage.setItem('smartinput-mobile-device-id', deviceId);
    } else {
      localStorage.removeItem('smartinput-mobile-device-id');
    }
  };

  const setConnected = (connected: boolean) => {
    isConnected.value = connected;
  };

  const setLoading = (loading: boolean) => {
    isLoading.value = loading;
  };

  const setLastError = (error: AppError | null) => {
    lastError.value = error;
    // 如果是错误，5秒后自动清除
    if (error) {
      setTimeout(() => {
        lastError.value = null;
      }, 5000);
    }
  };

  const clearError = () => {
    lastError.value = null;
  };

  const logout = () => {
    user.value = null;
    token.value = null;
    currentDeviceId.value = null;
    isConnected.value = false;
    localStorage.removeItem('smartinput-mobile-token');
    localStorage.removeItem('smartinput-mobile-device-id');
    localStorage.removeItem('smartinput-mobile-user');
  };

  const loadFromStorage = () => {
    const storedToken = localStorage.getItem('smartinput-mobile-token');
    const storedDeviceId = localStorage.getItem('smartinput-mobile-device-id');
    const storedUser = localStorage.getItem('smartinput-mobile-user');
    
    if (storedToken) {
      token.value = storedToken;
    }
    
    if (storedDeviceId) {
      currentDeviceId.value = storedDeviceId;
    }
    
    if (storedUser) {
      try {
        user.value = JSON.parse(storedUser);
      } catch (error) {
        console.error('解析存储的用户信息失败:', error);
        localStorage.removeItem('smartinput-mobile-user');
      }
    }
  };

  // 自动验证token的方法
  const validateStoredToken = async () => {
    if (token.value) {
      try {
        const { authAPI } = await import('@/services/api');
        const isValid = await authAPI.validateToken();
        if (!isValid) {
          console.log('存储的token已失效，清除登录状态');
          logout();
        } else {
          console.log('存储的token有效，保持登录状态');
        }
      } catch (error) {
        console.error('验证token失败:', error);
        logout();
      }
    }
  };

  // 初始化时加载存储的数据
  loadFromStorage();
  
  // 如果已登录，验证token有效性
  if (isLoggedIn.value) {
    validateStoredToken();
  }

  return {
    // 状态
    user,
    token,
    currentDeviceId,
    isConnected,
    isLoading,
    lastError,
    
    // 计算属性
    isLoggedIn,
    hasDevice,
    
    // 方法
    setUser,
    setToken,
    setCurrentDeviceId,
    setConnected,
    setLoading,
    setLastError,
    clearError,
    logout,
    loadFromStorage
  };
}); 